#!/usr/bin/env python
# -*- coding: utf-8 -*-
# PROJECT_NAME: D:\code\easyofd\easyofd\parser
# CREATE_TIME: 2023-07-27
# E_MAIL: renoyuan@foxmail.com
# AUTHOR: reno
# NOTE:  文件处理
import os
import base64
import shutil
from typing import Any
from uuid import uuid1

import xmltodict
import zipfile


class FileRead(object):
    """
    文件读取，清除
    'root': OFD.xml 
    "root_doc" Doc_0/Document.xml
    xml_path : xml_obj
    other_path : b64string
    """

    def __init__(self, unzip_path):
        pid = os.getpid()
        self.name = f"{pid}_{str(uuid1())}.ofd"
        self.pdf_name = self.name.replace(".ofd", ".pdf")
        self.unzip_path = unzip_path
        self.file_tree = {}

    def buld_file_tree(self):
        "xml读取对象其他b64"
        self.file_tree["root"] = self.unzip_path
        self.file_tree["pdf_name"] = self.pdf_name
        for root, dirs, files in os.walk(self.unzip_path):
            for file in files:
                abs_path = os.path.join(root, file)
                # 资源文件 则 b64 xml 则  xml——obj
                self.file_tree[abs_path] = str(base64.b64encode(open(f"{abs_path}", "rb").read()), "utf-8") \
                    if "xml" not in file else xmltodict.parse(open(f"{abs_path}", "r", encoding="utf-8").read())
        self.file_tree["root_doc"] = os.path.join(self.unzip_path, "OFD.xml") if os.path.join(self.unzip_path,
                                                                                              "OFD.xml") in self.file_tree else ""

    def __call__(self, *args: Any, **kwds: Any) -> Any:
        self.buld_file_tree()
        return self.file_tree
